package com.junzhiit.nengji.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.junzhiit.nengji.api.service.SendSmsService;
import com.junzhiit.nengji.api.web.util.APICodeStatus;
import com.junzhiit.nengji.api.web.util.aliyun.SmsUtil;
import com.junzhiit.nengji.api.web.util.aliyun.bean.SMSParams;
import com.junzhiit.nengji.api.web.vo.ResultVO;
import com.junzhiit.nengji.dao.SystemUserDAO;

@Service
public class SendSmsServiceImpl extends BaseServiceImpl implements SendSmsService {

	@Autowired
	private SystemUserDAO systemUserDAO;
	
	@Override
	public ResultVO getPhoneVerificationCode(String phoneNumber, String smsTemplateCode, Boolean isCheckPhone) {
		ResultVO result = new ResultVO();
		
		if(isCheckPhone){
			if(systemUserDAO.getMobilePhoneCount(phoneNumber) == 0){//检查是否存在该手机
				result.setStatus(APICodeStatus.MOBILE_PHONE_HAS_USED);
				result.setMessage("The phone does not exist.");
				return result;
			}
		}
		try {
			logger.info("get phone code ，the phone number is ="+phoneNumber);
			if(StringUtils.isBlank(smsTemplateCode)){
				smsTemplateCode = SmsUtil.ALIYUN_SMS_TEMPLATE_CODE;
			}
			//随机生成6位验证码
			String randCode = RandomStringUtils.randomNumeric(6);
			Integer timeInt = 10;//有效时间\分钟
			
			String[] phoneNumbers = {phoneNumber};
			String[] paramKeys = {"verificationCode"};
			String[] paramValues = {randCode};
			SMSParams smsParams = new SMSParams();
			smsParams.setSignName(SmsUtil.ALIYUN_SMS_SIGN_NAME);
			smsParams.setTemplateCode(smsTemplateCode);
			smsParams.setPhoneNumbers(phoneNumbers);
			smsParams.setParamKeys(paramKeys);
			smsParams.setParamValues(paramValues);
	        Boolean bl = SmsUtil.sendSmsToBoolean(smsParams);
	        
	        if(bl){
	        	//设置验证码有效时间为10分钟
				Date date = DateUtil.addMins(new Date(), timeInt);
				String time = DateUtil.formatTime(date);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("code", randCode);//校验码
				map.put("time", time);//有效时间
				result.setData(map);
				result.setMessage("the get phone code is success.");
	        }else{
	        	result.setStatus(APICodeStatus.GET_PHONE_CODE_FAILE);
				result.setMessage("the get phone code is  fail.");
	        }
		} catch (Exception e) {
			logger.error(e.getMessage());
			result.setStatus(APICodeStatus.GET_PHONE_CODE_FAILE);
        	result.setMessage(e.getMessage());
		}
		
		return result;
	}

}
